package com.focusai.efairy.network;

import android.os.Handler;
import android.os.Looper;

import com.facebook.stetho.okhttp3.StethoInterceptor;
import com.focusai.efairy.config.AppConfig;
import com.focusai.efairy.network.exception.NetworkException;
import com.focusai.efairy.network.request.base.Request;
import com.focusai.efairy.network.utils.HttpUtil;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Interceptor;

/**
 * Created by heqingbao on 2016/8/1.
 */
public final class HttpManager {

    private static HttpManager sInstance;

    private ResponseDelivery mResponseDelivery;
    private Network mNetwork;
//    private OkHttpOAuthConsumer mOauthConsumer;

    public static HttpManager getInstance() {
        if (sInstance == null) {
            synchronized (HttpManager.class) {
                if (sInstance == null) {
                    sInstance = new HttpManager();
                }
            }
        }

        return sInstance;
    }

    private HttpManager() {
//        mOauthConsumer = new OkHttpOAuthConsumer(EnvConfig.consumerKey(), EnvConfig.consumerSecret());

        List<Interceptor> interceptors = new ArrayList<>();
        interceptors.add(new RetryInterceptor());
//        interceptors.add(new SigningInterceptor(mOauthConsumer));

        List<Interceptor> networkInterceptors = new ArrayList<>();

        if (AppConfig.isDebugMode) {
            interceptors.add(new LoggingInterceptor());
            networkInterceptors.add(new StethoInterceptor());
        }
        String userAgent = HttpUtil.genUserAgent();

        mNetwork = new OkHttpNetwork(null, interceptors, networkInterceptors, userAgent);
        mResponseDelivery = new ExecutorDelivery(new Handler(Looper.getMainLooper()));
    }



    public <T> Response<T> performRequest(Request<T> request) {
        try {
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            return request.parseNetworkResponse(networkResponse);
        } catch (NetworkException e) {
            return Response.error(e);
        }
    }



    public long sendRequest(final Request request) {
        long requestId = mNetwork.sendRequest(request, new NetCallback() {

            @Override
            public void onError(NetworkException error) {
                mResponseDelivery.postError(request, error);
            }

            @Override
            public void onResponse(NetworkResponse networkResponse) {
                Response<?> resp = request.parseNetworkResponse(networkResponse);
                mResponseDelivery.postResponse(request, resp);
            }
        });

        return requestId;
    }

    public void cancelRequest(long requestId) {
        mNetwork.cancelRequest(requestId);
    }
}
